package com.cheyunkeji.er.fragment.fast_evaluate;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSS;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.common.OSSLog;
import com.alibaba.sdk.android.oss.common.auth.OSSCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSPlainTextAKSKCredentialProvider;
import com.baidu.ocr.sdk.OCR;
import com.baidu.ocr.sdk.OnResultListener;
import com.baidu.ocr.sdk.exception.OCRError;
import com.baidu.ocr.sdk.model.AccessToken;
import com.baidu.ocr.ui.camera.CameraActivity;
import com.cheyun.netsalev3.R;
import com.cheyunkeji.er.Constants;
import com.cheyun.netsalev3.MyApplication;
import com.cheyunkeji.er.activity.fast_evaluate.CarBrandSelectActivity;
import com.cheyunkeji.er.activity.fast_evaluate.FastEvaluateActivity;
import com.cheyunkeji.er.activity.fast_evaluate.FastEvaluateCitySelectActivity;
import com.cheyunkeji.er.activity.fast_evaluate.FastEvaluateMorePicturesActivity;
import com.cheyunkeji.er.activity.fast_evaluate.FastEvaluateReportActivity;
import com.cheyunkeji.er.activity.fast_evaluate.VehicleLicenseDatePickActivity;
import com.cheyunkeji.er.base.BaseFragment;
import com.cheyunkeji.er.bean.fast_evaluate.Car300CityInfoList;
import com.cheyunkeji.er.bean.fast_evaluate.Car300EvaluateReport;
import com.cheyunkeji.er.bean.fast_evaluate.CarModel;
import com.cheyunkeji.er.bean.fast_evaluate.DriveLicenseScanDataValue;
import com.cheyunkeji.er.bean.fast_evaluate.DriveLicenseScanRequestParams;
import com.cheyunkeji.er.bean.fast_evaluate.DriveLicenseScanResult;
import com.cheyunkeji.er.bean.fast_evaluate.PrevEvaluateRecord;
import com.cheyunkeji.er.http.ApiClient;
import com.cheyunkeji.er.http.HttpConstants;
import com.cheyunkeji.er.http.RespCallback;
import com.cheyunkeji.er.service.OssService;
import com.cheyunkeji.er.service.RecognizeService;
import com.cheyunkeji.er.utils.FileUtil;
import com.cheyunkeji.er.utils.ImageLoadUtil;
import com.cheyunkeji.er.utils.InputLowerToUpper;
import com.cheyunkeji.er.utils.PictureCompressUtil;
import com.cheyunkeji.er.utils.StringUtils;
import com.cheyunkeji.er.view.SDialog;
import com.cheyunkeji.er.view.SToast;
import com.cheyunkeji.er.view.TopBar;
import com.cheyunkeji.er.view.evaluate.ImageSelectDialog;
import com.dou361.dialogui.DialogUIUtils;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.google.gson.JsonSyntaxException;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;
import me.iwf.photopicker.PhotoPicker;
import me.iwf.photopicker.utils.ImageCaptureManager;
import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Request;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

import static android.app.Activity.RESULT_OK;

/**
 * @author Michael
 * @date 2017/4/13 16:17
 */


public class FastEvaluateFragment extends BaseFragment implements FastEvaluateActivity.onCarModelSelectedListener, SDialog.SDialogListener, OssService.onImageProcessedResultListener, ImageSelectDialog.ImageSelectListener, EasyPermissions.PermissionCallbacks {
    public static final int REQUEST_CODE_CITY = 0x1571;
    public static final int REQUEST_CODE_PALATE_DATE = 2;
    private static final String TAG = FastEvaluateFragment.class.getSimpleName();
    private static final int TAKE_LICENSE_PHOTO = 0x16;

    private static final int CAR_LEFT_FRONT_REQUEST_PERMISSIONS = 0X1001;
    private static final int CAR_TAKE_LICENSE_PHOTO_REQUEST = 0X1002;
    public static final String MORE_PICTURE = "MORE_PICTURES";
    private static final int REQUEST_CODE_MORE_PICTURES = 0X1003;

    private static CarModel selectedCarModel = null;
    private final int SELECT_LICENSE_PICTURE = 0X1101;
    private final int SELECT_CAR_LEFT_FRONT_IMG = 0X1102;

    public static final int REQUEST_CODE_CAR = 0X1103;

    /**
     * 存放“更多照片”中的 8 张照片
     */
    String[] morePictures = new String[]{"", "", "", "", "", "", "", ""};

    @BindView(R.id.v_topbar)
    TopBar vTopbar;
    @BindView(R.id.iv_license)
    ImageView ivLicense;
    @BindView(R.id.tv_car_model)
    TextView tvCarModel;
    @BindView(R.id.ll_car_model)
    RelativeLayout llCarModel;
    @BindView(R.id.tv_city)
    TextView tvCity;
    @BindView(R.id.ll_city_select)
    RelativeLayout llCitySelect;
    @BindView(R.id.ll_palate_date)
    RelativeLayout llPalateDate;
    @BindView(R.id.et_miles)
    EditText etMiles;
    @BindView(R.id.et_carowner_name)
    EditText etCarownerName;
    @BindView(R.id.et_contacts)
    EditText etContacts;
    @BindView(R.id.et_palate_number)
    EditText etPalateNumber;
    @BindView(R.id.et_vin)
    EditText etVin;
    @BindView(R.id.sv_content)
    ScrollView svContent;
    @BindView(R.id.iv_car_photo)
    ImageView ivCarPhoto;
    @BindView(R.id.ib_take_photo)
    ImageButton ibTakePhoto;
    @BindView(R.id.btn_fast_evaluate)
    Button btnFastEvaluate;
    @BindView(R.id.tv_palate_date)
    TextView tvPalateDate;
    @BindView(R.id.ll_root_view)
    LinearLayout llRootView;
    @BindView(R.id.tv_more_pictures)
    TextView tvMorePictures;

    @BindView(R.id.ll_car_model_tip)
    LinearLayout ll_car_model_tip;
    @BindView(R.id.tv_car_model_vv)
    TextView tv_car_model_vv;
    private String model_mark;

//    @BindView(R.id.topView)
//    View topView;

    private ImageCaptureManager captureManager;
    private SDialog sDialog;
    private Car300CityInfoList.CityListBean selectedCity;
    private String firstLicenseYearMonth;
    private DriveLicenseScanDataValue scanInfo;
    private Car300EvaluateReport car300EvaluateReport;
    private String carLeftFrontPictureUrl;
    private ImageSelectDialog imgSelectDialog;
    private String[] perms;

    //    行驶证图片路径
    private String licenseImgPath;
    private String appId = "";
    private String session_secret = "";
    private String api_type = ""; //aliyun  bdyun

    private PrevEvaluateRecord prevData = null;


    public static FastEvaluateFragment newInstance(PrevEvaluateRecord data){
        FastEvaluateFragment fragment = new FastEvaluateFragment();
        Bundle bundle = new Bundle();
        bundle.putSerializable( "prevData", data);
        fragment.setArguments(bundle);
        return fragment;
    }

    @Override
    protected void doInflaterView(LayoutInflater inflater, ViewGroup container) {
        contentView = inflater.inflate(R.layout.er_frag_fast_evaluate, container, false);
        ButterKnife.bind(this, contentView);
    }

    @Override
    protected void init() {
        captureManager = new ImageCaptureManager(getActivity());
    }

    @Override
    protected void initView() {
        vTopbar.setTitle("快速估价");
        vTopbar.setRight("扫行驶证", -1,60, this);
        llCarModel.setOnClickListener(this);
        llCitySelect.setOnClickListener(this);
        llPalateDate.setOnClickListener(this);
        ibTakePhoto.setOnClickListener(this);
        btnFastEvaluate.setOnClickListener(this);
        tvMorePictures.setOnClickListener(this);
        etVin.setTransformationMethod(InputLowerToUpper.getInstance());
//        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){
//            topView.setVisibility(View.GONE);
//        }
    }

    @Override
    protected void initData() {
        perms = new String[]{Manifest.permission.CAMERA, Manifest.permission.READ_EXTERNAL_STORAGE};

        if(null != getArguments()) {
            prevData = (PrevEvaluateRecord) getArguments().getSerializable("prevData");
            if (prevData != null) {
                etVin.setText(prevData.getVin());
                etPalateNumber.setText(prevData.getPlate());
                carLeftFrontPictureUrl = prevData.getZqb();
                ImageLoadUtil.loadImg(FastEvaluateFragment.this.getActivity(), carLeftFrontPictureUrl, ivCarPhoto);
                tvCarModel.setText(prevData.getBeforeModelName());
                MyApplication.getInstance().getCar300Ids().setCarBrandId(prevData.getBeforeBrand());
                MyApplication.getInstance().getCar300Ids().setCarSeriesId(prevData.getBeforeSeries());
                MyApplication.getInstance().getCar300Ids().setCarModelId(prevData.getBeforeSpec());

                CarModel carModel = new CarModel();
                carModel.setName(prevData.getBeforeModelName());
                carModel.setSyear(prevData.getSyear());
                carModel.setEyear(prevData.getEyear());
                carModel.setId(prevData.getBeforeSpec());
                carModel.setPrice("");
                carModelSelected(carModel);
            }
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.ll_car_model: {
                Intent intent = new Intent(getActivity(), CarBrandSelectActivity.class);
                intent.putExtra("Mark", model_mark);
                startActivity(intent);
                break;
            }
            case R.id.ll_city_select:
                startActivityForResult(new Intent(getActivity(), FastEvaluateCitySelectActivity.class), REQUEST_CODE_CITY);
                break;
            case R.id.ll_palate_date: {
                if (null != selectedCarModel) {
                    String[] startEndYear = new String[]{selectedCarModel.getSyear(), selectedCarModel.getEyear()};
                    Intent intent = new Intent(getActivity(), VehicleLicenseDatePickActivity.class);
                    intent.putExtra(Constants.CAR_MODEL_START_END_YEAR_ARRAY, startEndYear);
                    startActivityForResult(intent, REQUEST_CODE_PALATE_DATE);
                } else {
                    if (null == sDialog) {
                        sDialog = new SDialog(getActivity(), R.string.t_message_title, R.string.slected_car_model, FastEvaluateFragment.this);
                    } else {
                        sDialog.setContent(getResources().getString(R.string.slected_car_model));
                    }
                    sDialog.show();
                }
                break;
            }
//           选择车左前部图片
            case R.id.ib_take_photo:
                if (!EasyPermissions.hasPermissions(getActivity(), perms)) {
                    EasyPermissions.requestPermissions(this, "请选择必要权限", CAR_LEFT_FRONT_REQUEST_PERMISSIONS, perms);
                } else {
                    llRootView.setTag(SELECT_CAR_LEFT_FRONT_IMG);
                    showImgSelectDialog("车辆左前部");
                }
                break;
            case R.id.btn_fast_evaluate:
                uploadEvaluateData();
                break;
//           拍行驶证
            case R.id.vRight:
                //调用百度云扫描行驶证图片
                HashMap<String, String> params = new HashMap<>();
                params.put("device","Android");
//                params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());
//                params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
                ApiClient.postForm(HttpConstants.CHECK_LICENSE_AVAILABLE, params, new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (e instanceof UnknownHostException || e instanceof SocketException) {
                            SToast.show(R.string.tip_network_error, Gravity.CENTER);
                            return;
                        }
                    }
                    @Override
                    public void onResponse(String response, int id) {
                        try {
                            JSONObject obj = new JSONObject(response);
                            if (null != obj && obj.optString("code").equals("1")) {
                                try {
                                    JSONObject data = obj.getJSONObject("data");
                                    String aid = data.getString("appid");
                                    String api_key = data.getString("api_key");
                                    String secret_key = data.getString("secret_key");
                                    String license_path = data.getString("license_path");
                                    session_secret = data.getString("session_secret");
                                    api_type = data.getString("api_type");
                                    appId = aid;
                                    if(api_type.equals("aliyun")){
                                        if (!EasyPermissions.hasPermissions(getActivity(), perms)) {
                                            EasyPermissions.requestPermissions(FastEvaluateFragment.this, "请选择必要权限", CAR_TAKE_LICENSE_PHOTO_REQUEST, perms);
                                        } else {
                                            llRootView.setTag(SELECT_LICENSE_PICTURE);
                                            showImgSelectDialog("行驶证");
                                        }
                                    }else if(api_type.equals("bdyun")) {
                                        initAccessTokenWithAkSk(api_key,secret_key);
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            } else {
                                if (null == sDialog) {
                                    sDialog = new SDialog(getActivity(), R.string.t_message_title, obj.optString("msg"), FastEvaluateFragment.this);
                                } else {
                                    sDialog.setContent(obj.optString("msg"));
                                }
                                sDialog.show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    @Override
                    public void onBefore(Request request, int id) {
                        showDialog();
                    }
                    @Override
                    public void onAfter(int id) {
                        dismissDialog();
                    }
                });
                break;
            case R.id.tv_more_pictures:
                Intent intent = new Intent(getActivity(), FastEvaluateMorePicturesActivity.class);
                intent.putExtra(MORE_PICTURE, morePictures);
                startActivityForResult(intent, REQUEST_CODE_MORE_PICTURES);
                break;
            default:
                break;
        }
    }

    private void initAccessTokenWithAkSk(String ak,String sk) {
        OCR.getInstance(this.getActivity()).initAccessTokenWithAkSk(new OnResultListener<AccessToken>() {
            @Override
            public void onResult(AccessToken result) {
                String token = result.getAccessToken();
                getBaiduPhoto();
            }

            @Override
            public void onError(OCRError error) {
                error.printStackTrace();
                Log.e("AK，SK方式获取token失败", error.getMessage());
            }
        }, this.getActivity().getApplicationContext(),  ak,sk);
    }

    private static final int REQUEST_CODE_VEHICLE_LICENSE = 120;

    private void getBaiduPhoto(){
        Intent intent = new Intent(this.getActivity(), CameraActivity.class);
        intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                FileUtil.getSaveFile(this.getActivity().getApplication()).getAbsolutePath());
        intent.putExtra(CameraActivity.KEY_CONTENT_TYPE,
                CameraActivity.CONTENT_TYPE_GENERAL);
        startActivityForResult(intent, REQUEST_CODE_VEHICLE_LICENSE);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    /**
     * 上传评估数据，生成评估报告
     */
    private void uploadEvaluateData() {
        if (verifyInputLegality()) {
            getFastEvaluateReport(selectedCarModel.getId(), firstLicenseYearMonth,
                    etMiles.getText().toString(), selectedCity.getCity_id());
        }
    }

    /**
     * 获取车300评估报告信息
     *
     * @param modelId               车型id
     * @param firstLicenseYearMonth 首次上牌日期
     * @param miles                 行驶万公里数
     * @param cityId                城市id
     */
    private void getFastEvaluateReport(String modelId, String firstLicenseYearMonth, String miles, String cityId) {
        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        params.put("modelId", modelId);
        params.put("regDate", firstLicenseYearMonth);
        params.put("mile", miles);
        params.put("zone", cityId);
        for (String key : params.keySet()) {
            Log.e(TAG, "getFastEvaluateReport:   key : " + key + "\t value : " + params.get(key));
        }
        ApiClient.postForm(HttpConstants.CAR_300_GET_EVALUATE_INFO, params, new RespCallback<Car300EvaluateReport>() {

            @Override
            protected void onRequestFailed(String msg) {
                SToast.show(msg);
            }

            @Override
            protected void onSuccess(Car300EvaluateReport data) {
                car300EvaluateReport = data;
//                添加评估记录
                fastEvaluateAdd(data);
            }

            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }

            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });
    }

    public void showImgSelectDialog(String titleStr) {
        if (null == imgSelectDialog) {
            imgSelectDialog = new ImageSelectDialog(this.getActivity(), this, titleStr);
        } else {
            imgSelectDialog.setTitleStr(titleStr);
        }
        imgSelectDialog.show();
    }

    public void fastEvaluateAdd(Car300EvaluateReport evaluateData) {
        HashMap<String, String> params = new HashMap<>();
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        if (TextUtils.isEmpty(etVin.getText().toString())) {
            SToast.show("请输入VIN码");
            return;
        } else if (etVin.getText().toString().trim().length() != 17) {
            SToast.show("请输入正确的VIN");
            return;
        } else {
            params.put("vin", etVin.getText().toString());
        }
        if (TextUtils.isEmpty(etPalateNumber.getText().toString())) {
            SToast.show("请输入车牌号");
            return;
        } else {
            params.put("plate", etPalateNumber.getText().toString());
        }
        if (TextUtils.isEmpty(etCarownerName.getText().toString())) {
            SToast.show("请输入车主姓名");
            return;
        } else {
            params.put("owner_realname", etCarownerName.getText().toString());
        }
        if (TextUtils.isEmpty(etContacts.getText().toString())) {
            SToast.show("请输入联系电话");
            return;
        } else {
            params.put("owner_phone", etContacts.getText().toString());
        }
        params.put("brand", MyApplication.getInstance().getCar300Ids().getCarBrandId());
        params.put("series", MyApplication.getInstance().getCar300Ids().getCarSeriesId());
        params.put("spec", MyApplication.getInstance().getCar300Ids().getCarModelId());
        params.put("city", selectedCity.getCity_id());
        params.put("syear", selectedCarModel.getSyear());
        params.put("eyear", selectedCarModel.getEyear());

        String tempString = tvPalateDate.getText().toString().replace("年", "-").replace("月", "");
        params.put("licdate", tempString);
        Log.e(TAG, "firstLicenseYearMonth: =================== " + firstLicenseYearMonth);
        params.put("mileage", etMiles.getText().toString());
        params.put("emission", evaluateData.getDischarge_standard());

        if (TextUtils.isEmpty(carLeftFrontPictureUrl)) {
            SToast.show("请选择车辆左前部图片");
            return;
        } else {
            params.put("zqb", carLeftFrontPictureUrl);
        }
        params.put("proprice", String.valueOf(evaluateData.getPrice()));
        params.put("lowprice", getDifferentConditionPrice(evaluateData.getEval_prices(), "normal"));
        params.put("goodprice", getDifferentConditionPrice(evaluateData.getEval_prices(), "good"));
        params.put("highprice", getDifferentConditionPrice(evaluateData.getEval_prices(), "excellent"));
//      上传行驶证照片和 [更多照片]
        params.put("images", getAllOSSUploadedPictures());
        for (String string : params.keySet()) {
            Log.e(TAG, " ================== fastEvaluateAdd:  key : " + string + "\t\t value : " + params.get(string));
        }
        ApiClient.postForm(HttpConstants.FAST_EVALUATE_ADD, params, new StringCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {
                e.printStackTrace();
            }

            @Override
            public void onResponse(String response, int id) {
                try {
                    if (!TextUtils.isEmpty(response)) {
                        JSONObject jsonObject = new JSONObject(response);
                        if (1 == jsonObject.optInt("code")) {
                            JSONObject data = new JSONObject(new JSONObject(response).opt("data").toString());
                            Log.e(TAG, "onResponse:  push successfully " + data.toString());
                            String h5 = data.opt("h5").toString();
                            String pid = data.optString("pid");
                            String push_type = data.opt("push_type").toString();
                            String push_archive_type = data.opt("push_archive_type").toString();
                            String spec_name = data.optString("spec_name");
                            Log.e(TAG, "onResponse:  HTML5" + h5);
                            Log.e(TAG, "onResponse:  pid " + pid);
                            clearData();
                            Intent intent = new Intent(FastEvaluateFragment.this.getActivity(), FastEvaluateReportActivity.class);
                            intent.putExtra("data", new String[]{h5, pid, push_type, push_archive_type,spec_name,data.optString("zqb")});
                            startActivity(intent);
//                           延时两秒清空界面输入数据
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {
//                                    清除输入框数据
                                    clearInputData();
                                }
                            }, 2000);
                        } else {
                            showRemindDialog(jsonObject.optString("msg"));
                        }
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    /**
     * 快速估价成功，清除上一次评估数据
     */
    private void clearData() {
        licenseImgPath = null;
        for (int i = 0; i < morePictures.length; i++) {
            if (!TextUtils.isEmpty(morePictures[i])) {
                morePictures[i] = "";
            }
        }
    }

    /**
     * 按照后台要求，拼接行驶证 + 更多图片，以逗号隔开
     *
     * @return
     */
    private String getAllOSSUploadedPictures() {
        StringBuilder builder = new StringBuilder();
        if (!TextUtils.isEmpty(licenseImgPath)) {
            builder.append(licenseImgPath + ",");
        }
        for (int i = 0; i < morePictures.length; i++) {
            if (!TextUtils.isEmpty(morePictures[i])) {
                builder.append(morePictures[i] + ",");
            }
        }
        String result = builder.toString();
        if(TextUtils.isEmpty(result)){
            return "";
        }
        Log.e(TAG, "getAllOSSUploadedPictures: " + result );
        return result.substring(0,result.length()-1) ;
    }


    private String getDifferentConditionPrice(List<Car300EvaluateReport.EvalPricesBean> eval_prices, String conditionDesc) {
        if (null != eval_prices && eval_prices.size() != 0) {
            for (int i = 0; i < eval_prices.size(); i++) {
                if (eval_prices.get(i).getCondition().equals(conditionDesc)) {
                    return String.valueOf(eval_prices.get(i).getDealer_buy_price());
                }
            }
        }
        return null;
    }


    /**
     * 清空所有输入的数据
     */
    private void clearInputData() {
        ivLicense.setImageResource(R.drawable.er_sacn_license_default_img);
        tvCarModel.setText("");
        tvCity.setText("");
        tvPalateDate.setText("");
        etMiles.getText().clear();
        etCarownerName.getText().clear();
        etContacts.getText().clear();
        etPalateNumber.getText().clear();
        etVin.getText().clear();
//        etEngineNumber.getText().clear();
        ivCarPhoto.setImageResource(R.drawable.er_car_zuoqian);
        ivLicense.setVisibility(View.GONE);
    }


    /**
     * 校验输入数据完整性
     *
     * @return
     */
    private boolean verifyInputLegality() {
        if (TextUtils.isEmpty(tvCarModel.getText().toString())) {
            SToast.show("请选择车型");
            return false;
        }
        if (TextUtils.isEmpty(tvCity.getText().toString())) {
            SToast.show("请选择城市");
            return false;
        }
        if (TextUtils.isEmpty(tvPalateDate.getText().toString())) {
            SToast.show("请输入上牌日期");
            return false;
        }
        if (TextUtils.isEmpty(etMiles.getText().toString())) {
            SToast.show("请输入行驶里程");
            return false;
        }
        return true;
    }


    /**
     * 进入图片选择页面
     */
    private void pickPhoto() {
        PhotoPicker.builder()
                .setPhotoCount(1)
                .start(getActivity(), FastEvaluateFragment.this);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case PhotoPicker.REQUEST_CODE:
                if (data != null) {
                    String localImgPath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
                    ImageLoadUtil.loadImg(FastEvaluateFragment.this.getActivity(), localImgPath, ivCarPhoto);
                    showDialog();
                    initOSS(HttpConstants.OSS_END_POINT, HttpConstants.ALIYUN_OSS_BUCKET).asyncPutImage(OssService.getOssObjectInfo(true), localImgPath, "CAR_LEFT_FRONT");
//                    try {
//                        initOSS(HttpConstants.OSS_END_POINT, HttpConstants.ALIYUN_OSS_BUCKET).synchronizePutImage(OssService.getOssObjectInfo(true), localImgPath, "CAR_LEFT_FRONT");
//                    } catch (ClientException e) {
//                        e.printStackTrace();
//                    } catch (ServiceException e) {
//                        e.printStackTrace();
//                    }
                }
                break;
            case REQUEST_CODE_PALATE_DATE:
                if (resultCode == Constants.RESULT_CODE_OK) {
                    String selectedLicenseDate = data.getStringExtra(Constants.CAR_PALATE_YEAR_AND_MONTH);

                    if (!TextUtils.isEmpty(selectedLicenseDate)) {
                        firstLicenseYearMonth = selectedLicenseDate;
                        String[] yearMonth = selectedLicenseDate.split("-");
                        tvPalateDate.setText(yearMonth[0] + "年" + yearMonth[1] + "月");
                    }
                }
                break;
            case REQUEST_CODE_CITY:
                if (resultCode == Constants.RESULT_CODE_OK) {
                    if (null != data.getSerializableExtra(Constants.SELECTED_CITY_OBJECT)) {
                        selectedCity = (Car300CityInfoList.CityListBean) data.getSerializableExtra(Constants.SELECTED_CITY_OBJECT);
                        tvCity.setText(selectedCity.getCity_name());
                    }
                }
                break;
            case TAKE_LICENSE_PHOTO:
                if (resultCode == RESULT_OK) {
                    ivLicense.setVisibility(View.VISIBLE);
                    captureManager.galleryAddPic();
                    String licensePath = data.getStringArrayListExtra(PhotoPicker.KEY_SELECTED_PHOTOS).get(0);
                    ImageLoadUtil.loadImgWithoutAnimate(getActivity(), licensePath, ivLicense);
                    recognizeLicenseInfo(licensePath);
//                  上传行驶证图片
                    uploadDrivingLicense(licensePath);
                }
                break;
            case REQUEST_CODE_VEHICLE_LICENSE:{
                if(resultCode == RESULT_OK) {
//                    final Dialog dialog = DialogUIUtils.showLoadingHorizontal(this.getActivity(),"识别中",true,false,false,false).show();
                    final Dialog dialog = DialogUIUtils.showLoadingHorizontal(this.getActivity(),"识别中",true).show();
                    RecognizeService.recVehicleLicense(this.getActivity(), FileUtil.getSaveFile(this.getActivity().getApplicationContext()).getAbsolutePath(),
                            new RecognizeService.ServiceListener() {
                                @Override
                                public void onResult(String result) {
                                    DialogUIUtils.dismiss(dialog);
                                    System.out.println(result);
                                    Log.e(TAG, "notifySetDataAfterScanSuccessed: 扫描成功  百度 :" + result);
                                    verifyScanLicenseAvailability(new Runnable() {
                                        @Override
                                        public void run() {

                                        }
                                    });
                                    try {
                                        JSONObject scanInfo = new JSONObject(result);
                                        notifySetDataAfterScanSuccessedBaidu(scanInfo);
                                    } catch (Exception e) {
                                        SToast.show("行驶证扫描失败，请重试！");
                                        Log.e(TAG, "notifySetDataAfterScanSuccessed: 解析失败  百度 :" + e.toString());
                                    }
                                }
                            });
                }
                break;
            }
            case ImageCaptureManager.REQUEST_TAKE_PHOTO:
                if (resultCode == RESULT_OK) {
                    captureManager.galleryAddPic();
                    String path = captureManager.getCurrentPhotoPath();
                    if ((int) llRootView.getTag() == SELECT_LICENSE_PICTURE) {
                        ivLicense.setVisibility(View.VISIBLE);
                        ImageLoadUtil.loadImgWithoutAnimate(getActivity(), path, ivLicense);
                        recognizeLicenseInfo(path);
                    } else {
                        ImageLoadUtil.loadImg(FastEvaluateFragment.this.getActivity(), path, ivCarPhoto);
                        showDialog();
                        initOSS(HttpConstants.OSS_END_POINT, HttpConstants.ALIYUN_OSS_BUCKET).asyncPutImage(OssService.getOssObjectInfo(true), path, "CAR_LEFT_FRONT");
                    }
                }
                break;
            case REQUEST_CODE_MORE_PICTURES:
                if (resultCode == Activity.RESULT_OK) {
                    String[] picArray = data.getStringArrayExtra(MORE_PICTURE);
//                  校验是否返回长度为 8 的 String 数组
                    if (null != picArray && picArray.length == morePictures.length) {
                        morePictures = picArray;
                    }
                    for (int i = 0; i < picArray.length; i++) {
                        Log.e(TAG, "onActivityResult the returned Picture Path : " + picArray[i]);
                    }
                }
            default:
                break;
        }
    }

    /**
     * 上传行驶证照片
     *
     * @param licensePath
     */
    private void uploadDrivingLicense(String licensePath) {
        Observable.just(licensePath)
                .map(new Function<String, OssService.OssUnit>() {
                    @Override
                    public OssService.OssUnit apply(String imgPath) throws Exception {
                        return MyApplication.getInstance().getOssService(null).synchronizePutImage(OssService.getOssObjectInfo(true),
                                imgPath, "");
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<OssService.OssUnit>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        Log.e(TAG, "onSubscribe: ");
                    }

                    @Override
                    public void onNext(OssService.OssUnit ossUnit) {
                        if (!TextUtils.isEmpty(ossUnit.getPath())) {
                            Log.e(TAG, "onNext: 行驶证照片 ： " + ossUnit.getPath());
                            licenseImgPath = ossUnit.getPath();
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
//                        行驶证上传失败
                        Log.e(TAG, "onError: " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {
                        Log.e(TAG, "onComplete: 行驶证照片上传成功");
                    }
                });
    }


    /**
     * 识别行驶证信息
     *
     * @param currentPhotoPath photo path
     */
    private void recognizeLicenseInfo(String currentPhotoPath) {
//      获取图片64编码
        String imgBase64 = PictureCompressUtil.compressImageReturnAsBase64String(currentPhotoPath, getActivity());
        if (!TextUtils.isEmpty(imgBase64)) {
            List<DriveLicenseScanRequestParams.InputsBean> inputs = new ArrayList<>();
//            按照阿里云行驶证扫描接口传参
            inputs.add(new DriveLicenseScanRequestParams.InputsBean(new DriveLicenseScanRequestParams.InputsBean.ImageBean(50, imgBase64)));
            DriveLicenseScanRequestParams request = new DriveLicenseScanRequestParams(inputs);
            OkHttpUtils
                    .postString()
                    .url(HttpConstants.DRIVE_LICENSE_SCAN_INFO_ALIYUN)
                    .addHeader("Authorization", "APPCODE " + HttpConstants.DRIVE_LICENSE_SCAN_INTERFACE_APPCODE)
                    .content(new Gson().toJson(request))
                    .mediaType(MediaType.parse("application/json; charset=utf-8"))
                    .build()
                    .execute(new StringCallback() {

                        @Override
                        public void onError(Call call, Exception e, int id) {

                            if (null == sDialog) {
                                sDialog = new SDialog(getActivity(), R.string.t_message_title, R.string.scan_eoor, FastEvaluateFragment.this);
                            } else {
                                sDialog.setContent(getResources().getString(R.string.scan_eoor));
                            }
                            sDialog.show();
                        }

                        @Override
                        public void onResponse(String response, int id) {
                            Log.e(TAG, "onResponse: " + response);
                            DriveLicenseScanResult scanResult = null;
                            try {
                                scanResult = new Gson().fromJson(response, DriveLicenseScanResult.class);
                            } catch (JsonSyntaxException e) {
                                e.printStackTrace();
                            } catch (IllegalStateException e) {
                                e.printStackTrace();
                            }
                            if (null != scanResult) {
                                notifySetDataAfterScanSuccessed(scanResult);
                            } else {
                                if (null == sDialog) {
                                    sDialog = new SDialog(getActivity(), R.string.t_message_title, R.string.scan_failed, FastEvaluateFragment.this);
                                } else {
                                    sDialog.setContent(getResources().getString(R.string.scan_failed));
                                }
                                sDialog.show();
                            }
                        }

                        @Override
                        public void onBefore(Request request, int id) {
                            showDialog();
                        }

                        @Override
                        public void onAfter(int id) {
                            dismissDialog();
                        }

                    });

        }

    }

    /**
     * 提示框Dialog
     *
     * @param remindContentStr
     */
    public void showRemindDialog(String remindContentStr) {
        if (null == sDialog) {
            sDialog = new SDialog(getActivity(), R.string.t_message_title, remindContentStr, FastEvaluateFragment.this);
        } else {
            sDialog.setContent(remindContentStr);
        }
        sDialog.show();
    }


    /**
     * 扫描行驶证信息成功后，填充数据 (阿里云)
     *
     * @param scanResult
     */
    private void notifySetDataAfterScanSuccessed(DriveLicenseScanResult scanResult) {
        String rawDataValue = scanResult.getOutputs().get(0).getOutputValue().getDataValue();
        int a = rawDataValue.indexOf("{");
        int b = rawDataValue.lastIndexOf("}");
        String dataValue = rawDataValue.substring(a, b + 1);
        Log.e(TAG, "notifySetDataAfterScanSuccessed: dataValue " + dataValue);
        if (!TextUtils.isEmpty(dataValue)) {
            scanInfo = new Gson().fromJson(dataValue, DriveLicenseScanDataValue.class);
            if (null != scanInfo && scanInfo.isSuccess()) {
                Log.e(TAG, "notifySetDataAfterScanSuccessed: 扫描成功  首次上牌时间为 ： " + scanInfo.getRegister_date().length());
//              扫描结果完整，请求扣费接口后再显示
                if (!TextUtils.isEmpty(scanInfo.getOwner()) && !TextUtils.isEmpty(scanInfo.getPlate_num())
                        && !TextUtils.isEmpty(scanInfo.getVin()) && !TextUtils.isEmpty(scanInfo.getRegister_date()) && scanInfo.getRegister_date().length() == 8) {
                    verifyScanLicenseAvailability(new Runnable() {
                        @Override
                        public void run() {
                            etCarownerName.setText(scanInfo.getOwner());
                            etPalateNumber.setText(scanInfo.getPlate_num());
                            etVin.setText(scanInfo.getVin());
                            tvPalateDate.setText(new StringBuffer().append(scanInfo.getRegister_date().substring(0, 4)).append("年").append(scanInfo.getRegister_date().substring(4, 6)).append("月"));
                            firstLicenseYearMonth = tvPalateDate.getText().toString().replace("年", "-").replace("月", "");
                        }
                    });
                } else {
//                  扫描结果不完整，直接填入
                    etCarownerName.setText(scanInfo.getOwner());
                    etPalateNumber.setText(scanInfo.getPlate_num());
                    etVin.setText(scanInfo.getVin());
                    if (!TextUtils.isEmpty(scanInfo.getRegister_date()) && scanInfo.getRegister_date().length() == 8) {
                        tvPalateDate.setText(new StringBuffer().append(scanInfo.getRegister_date().substring(0, 4)).append("年").append(scanInfo.getRegister_date().substring(4, 6)).append("月"));
                        firstLicenseYearMonth = tvPalateDate.getText().toString().replace("年", "-").replace("月", "");
                    } else {
                        tvPalateDate.setText("");
                    }
                }
            } else {
                if (null == sDialog) {
                    sDialog = new SDialog(getActivity(), R.string.t_message_title, R.string.verify_failed, FastEvaluateFragment.this);
                } else {
                    sDialog.setContent(getResources().getString(R.string.verify_failed));
                }
                sDialog.show();
            }
        }
    }

    /**
     * 扫描行驶证信息成功后，填充数据 (百度)
     *
     * @param scanResult
     */
    private void notifySetDataAfterScanSuccessedBaidu(JSONObject scanResult) throws JSONException {
        boolean success = true;
        if(scanResult == null){
            success = false;
        }else{
            if(scanResult.has("words_result")){
                JSONObject result = scanResult.getJSONObject("words_result");
                final String owner = result.getJSONObject("所有人").getString("words");
                final String plate_num = result.getJSONObject("号牌号码").getString("words");
                final String vin = result.getJSONObject("车辆识别代号").getString("words");
                String register_date = "";
                if(result.has("注册日期")){
                    register_date = result.getJSONObject("注册日期").getString("words");
                }
                if(result.has("注册登记日期")){
                    register_date = result.getJSONObject("注册登记日期").getString("words");
                }
//              扫描结果完整，请求扣费接口后再显示
                if (!TextUtils.isEmpty(owner) && !TextUtils.isEmpty(plate_num)
                        && !TextUtils.isEmpty(vin) && !TextUtils.isEmpty(register_date) && register_date.length() == 8) {

                    etCarownerName.setText(owner);
                    etPalateNumber.setText(plate_num);
                    etVin.setText(vin);
                    tvPalateDate.setText(new StringBuffer().append(register_date.substring(0, 4)).append("年").append(register_date.substring(4, 6)).append("月"));
                    firstLicenseYearMonth = tvPalateDate.getText().toString().replace("年", "-").replace("月", "");

                } else {
//                  扫描结果不完整，直接填入
                    etCarownerName.setText(owner);
                    etPalateNumber.setText(plate_num);
                    etVin.setText(vin);
                    if (!TextUtils.isEmpty(register_date) && register_date.length() == 8) {
                        tvPalateDate.setText(new StringBuffer().append(register_date.substring(0, 4)).append("年").append(register_date.substring(4, 6)).append("月"));
                        firstLicenseYearMonth = tvPalateDate.getText().toString().replace("年", "-").replace("月", "");
                    } else {
                        tvPalateDate.setText("");
                    }
                }
                if(!TextUtils.isEmpty(vin)){
                    checkVin(vin);
                }
            }else{
                success = false;
            }
        }
        if (!success) {
            if (null == sDialog) {
                sDialog = new SDialog(getActivity(), R.string.t_message_title, R.string.verify_failed, FastEvaluateFragment.this);
            } else {
                sDialog.setContent(getResources().getString(R.string.verify_failed));
            }
            sDialog.show();
        }
    }


    private void verifyScanLicenseAvailability(final Runnable successUITask) {
        HashMap<String, String> params = new HashMap<>();
        params.put("appid",appId);
        params.put("session_secret",session_secret);
        //      params.put("authkey", UserInfoManager.getInstance(MyApplication.getInstance()).getAuthKey());//        params.put(ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getYkey(), ChannelInfoUtil.getCurrentChannelInfo().getCkey1().getY7e_e73a691f02a46500201c3998e6a2989d());
        ApiClient.postForm(HttpConstants.STATISTICS_SCAN_LICENSE_COUNT, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }
            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject obj = new JSONObject(response);
                    if (obj.optInt("code") == 1 && null != successUITask) {
                        successUITask.run();
                    } else if (obj.optString("code").equals("-30")) {
                        if (null == sDialog) {
                            sDialog = new SDialog(getActivity(), R.string.t_message_title, obj.optString("msg"), FastEvaluateFragment.this);
                        } else {
                            sDialog.setContent(obj.optString("msg"));
                        }
                        sDialog.show();
                    } else {
                        SToast.show(obj.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }
            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });
    }

    /**
     * 初始化一个OssService用来上传下载
     */
    public OssService initOSS(String endpoint, String bucket) {
        //如果希望直接使用accessKey来访问的时候，可以直接使用OSSPlainTextAKSKCredentialProvider来鉴权。
        OSSCredentialProvider credentialProvider = new OSSPlainTextAKSKCredentialProvider(HttpConstants.OSS_ACCESS_KEYID, HttpConstants.OSS_ACCESS_KEY_SECRET);
        ClientConfiguration conf = new ClientConfiguration();
        conf.setConnectionTimeout(15 * 1000); // 连接超时，默认15秒
        conf.setSocketTimeout(15 * 1000); // socket超时，默认15秒
        conf.setMaxConcurrentRequest(5); // 最大并发请求书，默认5个
        conf.setMaxErrorRetry(2); // 失败后最大重试次数，默认2次
        OSS oss = new OSSClient(MyApplication.getInstance().getApplicationContext(), endpoint, credentialProvider, conf);

//        OSS oss = new OSSClient(MyApplication.getInstance().getApplicationContext(), endpoint, credentialProvider);
        return new OssService(oss, bucket, FastEvaluateFragment.this);
    }

    @Override
    public void carModelSelected(CarModel carModel) {
        selectedCarModel = carModel;
        tvCarModel.setText(carModel.getName());
    }

    @Override
    public void onOK() {

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        sDialog = null;
        ApiClient.cancel(HttpConstants.CAR_300_GET_EVALUATE_INFO);
        ApiClient.cancel(HttpConstants.FAST_EVALUATE_ADD);
    }

    /**
     * 图片上传成功回调，返回图片的OSS url
     *
     * @param imgUrl
     */
    @Override
    public void onUploadOk(String imgUrl, Object tag) {
        carLeftFrontPictureUrl = imgUrl;
        dismissDialog();
        Log.e(TAG, "onUploadOk: Uploaded img url : " + carLeftFrontPictureUrl + "/n " + tag);
    }

    /**
     * 图片上传失败回调
     */
    @Override
    public void onUploadFailed() {
        dismissDialog();
        SToast.show("图片上传失败！");
    }

    private void openSystemCamera() {
        Intent intent = null;
        try {
            intent = captureManager.dispatchTakePictureIntent();
            startActivityForResult(intent, ImageCaptureManager.REQUEST_TAKE_PHOTO);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onTakePhotoWithSystemCamera() {
        openSystemCamera();
    }

    @Override
    public void onSelectImgOnGallery() {
        if ((int) llRootView.getTag() == SELECT_LICENSE_PICTURE) {
            PhotoPicker.builder()
                    .setPhotoCount(1)
                    .start(getActivity(), FastEvaluateFragment.this, TAKE_LICENSE_PHOTO);
        } else {
            pickPhoto();
        }
    }

    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        if (requestCode == CAR_LEFT_FRONT_REQUEST_PERMISSIONS) {
            llRootView.setTag(SELECT_CAR_LEFT_FRONT_IMG);
            showImgSelectDialog("车辆左前部");
        } else if (requestCode == CAR_TAKE_LICENSE_PHOTO_REQUEST) {
            llRootView.setTag(SELECT_LICENSE_PICTURE);
            showImgSelectDialog("行驶证");
        }
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
//      是否勾选了“不再询问”从而永久否定了权限，如果选中了则弹出进入设置入口的弹框，进行设置页面手动勾选中权限
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).build().show();
        }
    }

    private void checkVin(String vin){
        final HashMap<String, String> params = new HashMap<>();
        params.put("vin", vin);

        ApiClient.postForm(HttpConstants.getVinForText, params, new StringCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                if (e instanceof UnknownHostException || e instanceof SocketException) {
                    SToast.show(R.string.tip_network_error, Gravity.CENTER);
                    return;
                }
            }
            @Override
            public void onResponse(String response, int id) {
                try {
                    JSONObject obj = new JSONObject(response);
                    if (obj.optInt("code") == 1 ) {
                        JSONObject data = new JSONObject(new JSONObject(response).opt("data").toString());
                        String modelName = data.getString("modelName");
                        if(!StringUtils.isEmpty(modelName)){
                            ll_car_model_tip.setVisibility(View.VISIBLE);
                            tv_car_model_vv.setText(modelName);
                            model_mark = modelName;
                        }
                    } else {
                        SToast.show(obj.optString("msg"));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
            @Override
            public void onBefore(Request request, int id) {
                showDialog();
            }
            @Override
            public void onAfter(int id) {
                dismissDialog();
            }
        });
    }

}
